<?php
namespace Backend\Controllers;

use Models\Accesstoken;

class AppmainController extends BaseController
{
    public function beforeExecuteRoute($dispatcher)
    {
        parent::beforeExecuteRoute($dispatcher);

    }


    public function indexAction($out)
    {
        $Cuser = $this->Cuser;
        $accesstoken = Accesstoken::findFirstByuid($Cuser->uid);
        if ($accesstoken) {
            $accesstoken->accesstoken = md5(uniqid(rand()));
            $accesstoken->save();
        } else {
            $accesstoken = new Accesstoken();
            $accesstoken->uid = $Cuser->uid;
            $accesstoken->accesstoken = md5(uniqid(rand()));
            $accesstoken->save();
        }

        if ($this->hasApp($out, $Cuser)) {

        } else {
            return $this->response->redirect("admin/index");
        }
        $this->view->setVar('accesstoken', $accesstoken->accesstoken);
        $this->view->setVar('app',$out);
    }


    private function hasApp($out, $Cuser)
    {
        $appuser = $Cuser->getAppUser("end>'" . date("Y-m-d H:i:s", strtotime("now")) . "'");
        foreach ($appuser as $AppUser) {
            if ($out == $AppUser->App->action) {
                return true;
            }
        }
    }
}